<?php
	require '../include/library.inc.php';
	require '../include/admin_login.inc.php';

$school_id = intval(($_GET['school_id'])?$_GET['school_id']:$_POST['school_id']);
if (!$school_id) redirect("schools.php");

	
# Ако запазваме	
if ($_POST['is_submitted']) {
    $error_message = '';
    
	# Проверки
	if (!$_POST['name'])  $error_message .= 'School Name is required<br/>';
	
	if (!$_POST['sef_url'])  $error_message .= 'SEF URL is required<br/>';
	elseif(!preg_match('/^[0-9A-Za-z\-\_]+$/', $_POST['sef_url'])) $error_message .= 'SEF URL is invalid<br/>';
	
	$sql = "SELECT
				school_id
			FROM
				schools
			WHERE
				sef_url = '".$_POST['sef_url']."'
			AND
				school_id <> ".$school_id."
			  ";
	$result = query($sql);
	if ($row_seo = mysql_fetch_object($result)) $error_message .= 'The SEF URL already used by another school<br/>';
	
	if (!$_POST['description'])  $error_message .= 'Description is required<br/>';
	if (!$_POST['city_id'])  $error_message .= 'City is required<br/>';
    if (!$_POST['terms'])  $error_message .= 'Terms & Conditions are required<br/>';
	
	# OK
    if(!$error_message) {
				
		# Update the school
		$sql = 'UPDATE schools
				SET
					name = \''.escape($_POST['name']).'\', 
					sef_url = \''.escape($_POST['sef_url']).'\', 
					description = \''.escape($_POST['description']).'\', 
					meta_description = \''.escape($_POST['meta_description']).'\', 
					terms = \''.escape($_POST['terms']).'\', 
					city_id = '.intval($_POST['city_id']).', 
					address = \''.escape($_POST['address']).'\', 
					lat = \''.floatval($_POST['lat']).'\', 
					lng = \''.floatval($_POST['lng']).'\', 
					published = '.intval($_POST['published']).'
				WHERE
					school_id = '.$school_id.'
				';
		query($sql);
		
		
		# Images
		for($i=1;$i<4;$i++){
			if (is_uploaded_file($_FILES['image_'.$i]['tmp_name'])) {
				
				$upload_path = "../uploads/img/";
				
				$tmp_file = $_FILES['image_'.$i]['tmp_name'];
				$exp = explode('.',$_FILES['image_'.$i]['name']);
				$img_type = strtolower(end($exp));
				
				$sql = 'INSERT INTO images
							(school_id)
						VALUES
							('.$school_id.')
				';
				query($sql);
				$image_id = mysql_insert_id();
				
				if(copy($tmp_file, $upload_path.'img_'.$_POST['sef_url'].'_'.$image_id.'.'.$img_type)) {
					
					$sql = 'UPDATE images
							SET
								filename = \''.'img_'.$_POST['sef_url'].'_'.$image_id.'.'.$img_type.'\'
							WHERE
								image_id = '.$image_id.'
							  ';
					query($sql);
					
				} else{
					
					$sql = 'DELETE FROM 
							   images
							WHERE
							   image_id = '.$image_id.'
							 ';
					query($sql);
					$_SESSION['message'] .= 'Upload error for image '.$i.'. ';
					
				}
			}
		}
	  
	  	# Качване на logo
		if (is_uploaded_file($_FILES['logo']['tmp_name'])) {
			
			$upload_path = "../uploads/logos/";
			
			$tmp_file = $_FILES['logo']['tmp_name'];
			$exp = explode('.',$_FILES['logo']['name']);
			$img_type = strtolower(end($exp));
			
			$new_name = 'school_'.$school_id.'_logo.'.$img_type;
			
			if(copy($tmp_file, $upload_path.$new_name)) {
				
				$sql = 'UPDATE schools
						SET
							logo = \''.$new_name.'\'
						WHERE
							school_id = '.$school_id.'
				';
				query($sql);
				
			} else{
				
				$_SESSION['message'] .= 'The logo was not uploaded!';
				
			}
		}
			
      
		$_SESSION['message'] = 'School '.$_POST['name'].' was updated!';
		redirect("schools.php");
	  
    } else { //Има грешка
		
		$row_school =& $_POST;
		
	}
	
} else { //Първоначално зареждане
	
	$sql = 'SELECT
			  *
			FROM
			  schools
			WHERE
			  school_id = '.$school_id.'
		';
	$row_school = mysql_fetch_assoc(query($sql));
	
	if(!$row_school['school_id']) redirect("schools.php");
	
}


head_admin("School Edit");
?>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	mode : "exact",
    elements : "description, terms",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,

	// Drop lists for link/image/media/template dialogs
	//template_external_list_url : "js/template_list.js",
	external_link_list_url : "js/link_list.php",
	//media_external_list_url : "js/media_list.js",
	//external_image_list_url : "js/image_list.php"
	
});
</script>
		
		<?php if ($error_message) { ?>
		  <div class="message red">
			<h4>Error!</h4>
			<?=$error_message?>
		  </div>
		<?php } ?>
		
		
		
            <div class="topbuttons">
            	<a href="schools.php">Back to schools</a>
            </div>
            
            <h3>School Edit</h3>
            
            <form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
            <input type="hidden" name="school_id" value="<?=$school_id?>" />
            
			<dl class="clearfix">
			
			<dt><label class="required">School Name</label></dt>
            <dd><input class="inputbox w500" name="name" type="text" value="<?=sth($row_school['name'])?>" ></dd>            
			
			<dt><label class="required">SEF URL (Search Engine Friendly link. For Example: name-of-the-school)</label></dt>
            <dd><?=HTML_BASE?>school/<input class="inputbox w250" name="sef_url" type="text" value="<?=$row_school['sef_url']?>" ></dd>
			
            <dt><label class="required">Description</label></dt>
            <dd><textarea id="description" name="description" rows="24" style="width:100%" ><?=sth($row_school['description'])?></textarea></dd>
			
			<dt><label>Meta description</label></dt>
            <dd><textarea class="inputbox w500" name="meta_description" rows="3"><?=sth($row_school['meta_description'])?></textarea></dd>
            
            
            <dt><label class="required">Terms &amp; Conditions</label></dt>
            <dd><textarea id="terms" name="terms" rows="15" style="width:100%" ><?=sth($row_school['terms'])?></textarea></dd>
            
            </dl>
            
            <h4>Location</h4>
            <dl>
            
            <dt><label class="required">City</label></dt>
			<dd><select class="inputbox w250" name="city_id">
            <option value="">Choose city</option>
            <?php
			$sql = "SELECT
						ci.city_id,
						ci.name AS city,
						co.name AS country
					FROM
						cities AS ci,
						countries AS co
					WHERE
						ci.country_id = co.country_id
					ORDER BY
						ci.country_id
					  ";
			$result = query($sql);
            while ($row_city = mysql_fetch_object($result)) {
				echo '<option value="'.$row_city->city_id.'" '.(($row_school['city_id']==$row_city->city_id)?' selected':'').'>'.$row_city->city.', '.$row_city->country.'</option>';
			}
			?>
            </select></dd>
            
            <dt><label>Street Address</label></dt>
            <dd><textarea class="inputbox w500" name="address" rows="2"><?=sth($row_school['address'])?></textarea></dd>
            
            <dt><label>Coordinates</label></dt>
            <dd>
            <input class="inputbox" style="width:120px;" id="lat" name="lat" type="text" value="<?=$row_school['lat']?>" maxlength="20" />
            <input class="inputbox" style="width:120px;" id="lng" name="lng" type="text" value="<?=$row_school['lng']?>" maxlength="20" />
            </dd>
            
            </dl>
            
            <h4>Images (300x250px)</h4>
            
            <a name="images"></a>
            <dl>
            
            <?php
            $sql = 'SELECT
					  *
					FROM
					  images
					WHERE
					  school_id = '.$school_id.'
					ORDER BY
					  image_id
				';
			$result = query($sql);
			$i=1;
			while ($row_image = mysql_fetch_object($result)) {
			?>
            
            <div class="img_options">
            	<div class="del">
                <a onClick="if (window.confirm('Do you really want to delete this image?')) { document.location='school_image_del.php?image_id=<?=$row_image->image_id?>&school_id=<?=$school_id?>'; return false; }" class="delete" title="Delete">Delete</a>
                </div>
            	<img src="<?=HTML_BASE.'uploads/img/'.$row_image->filename?>" />
            </div>
            
            <?php
				$i++;
			}
			
			for ($j=$i;$j<4;$j++) {
			?>
            <dt><label>Image <?=$j?></label></dt>
            <dd><input class="inputbox w500" name="image_<?=$j?>" type="file" /></dd>
            
            <?php
			}
			?>
            
            </dl>
            
            <dl>
            
            <img src="<?=HTML_BASE.'uploads/logos/'.$row_school['logo']?>" align="right" border="1" />
            
            <dt><label>Change the logo (height: 100px)</label></dt>
            <dd><input class="inputbox w500" name="logo" type="file" /></dd>
            
            <dd><label>
			<input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($row_school['published'])?"checked=\"checked\"":"")?> />
			Published</label></dd>
            
                        
			<dd class="submit">
            <input type="submit" name="submit" id="submit" value="Save">
            </dd>
			
            </dl>
            
            
            <a name="courses"></a>
            <div class="topbuttons">
            	<a class="add" href="course_new.php?school_id=<?=$school_id?>&school_name=<?=sth($row_school['name'])?>">Add new course</a>
            </div>
            
            <h4><?=sth($row_school['name'])?> Courses</h4>
            
            <?php if ($_SESSION['message']) { ?>
			<div class="message green">
				<?=$_SESSION['message']?>
			</div>
			<?php unset($_SESSION['message']); } ?>
            
        <?php
        $sql = "SELECT
			c.course_id,
			c.name,
			c.registration_fee,
			c.published,
			t.name AS type
		FROM
		  	courses AS c,
			course_types AS t
		WHERE
			c.course_type_id = t.course_type_id
		AND	
			school_id = ".$school_id."
		  ";
		$result = query($sql);
		?>
        	
        <table id="listing" width="100%" cellpadding="0" cellspacing="0">
			<thead>
				<tr>
                    <td>Course Name</td>
                    <td>Course Type</td>
                    <td>Dates &amp; Durations</td>
                    <td>Application fee</td>
                    <td>Options</td>
				</tr>
			</thead>
			<tbody>
			<?php
	  
			  $i=1;
			  while ($row_course = mysql_fetch_object($result)) {				  
			?>
                <tr class="<?=(($i%2)?"none":"zebra")?>">
                    
                    <td>
                        <a href="course_edit.php?course_id=<?=$row_course->course_id?>&school_name=<?=sth($row_school['name'])?>" title="Edit"><?=$row_course->name?></a>
                    </td>
                    
                    <td><?=$row_course->type?></td>
                    
                    <td>
                    <dd><select class="inputbox" style="width:300px;" name="course_dates">
                    <?php
                    $sql = "SELECT
                                start_date,
								duration,
								tuition
								
                            FROM
                                course_dates
                            WHERE
                                course_id = ".$row_course->course_id."
                            ORDER BY
                                start_date, duration
                              ";
                    $rs_date = query($sql);
                    while ($row_dates = mysql_fetch_object($rs_date)) {
                        echo '<option>'.$row_dates->start_date.', '.$row_dates->duration.' weeks, $'.$row_dates->tuition.'</option>';
                    }
                    ?>
                    </select>
                    &nbsp; &nbsp; &nbsp;
                    <a href="course_dates.php?course_id=<?=$row_course->course_id?>&school_name=<?=sth($row_school['name'])?>" class="add" title="Manage Dates"></a>
                    </dd>
                    </td>
                                                            
                    <td>$<?=$row_course->registration_fee?></td>
                                                            
                    <td class="icons">
                        
                        <?php if ($row_course->published) { ?>
                         <a href="course_publish.php?course_id=<?=$row_course->course_id?>&publish=0&school_id=<?=$school_id?>" class="turn_on" name="turn_on" title="Unpublish"></a>
                        <?php } else { ?> 
                         <a href="course_publish.php?course_id=<?=$row_course->course_id?>&publish=1&school_id=<?=$school_id?>" class="turn_off" name="turn_off" title="Publish"></a>
                        <?php } ?>	
                        
                                     
                        <a href="course_edit.php?course_id=<?=$row_course->course_id?>&school_name=<?=sth($row_school['name'])?>" class="edit" title="Edit">Edit</a> 
                        
                        <a onClick="if (window.confirm('Do you really want to delete this course?\n<?=$row_course->course_name?>')) { document.location='course_del.php?course_id=<?=$row_course->course_id?>&school_id=<?=$school_id?>'; return false; }" class="delete" title="Delete">Delete</a>
                        
                    </td>
                    
                </tr>
                    
			 <?php
                  $i++;    
                } 
             ?>	
		 		  
			</tbody>
		</table>
            
            
                        
			</form>
            
<?php
	foot_admin(); 
?>